package com.zeus.base.smscenter.interceptor;

import com.zeus.base.smscenter.shiro.ShiroAjaxUtil;
import com.zeus.base.smscenter.shiro.ShiroError;
import com.zeus.base.smscenter.shiro.ShiroUtil;
import com.zeus.base.smscenter.utils.ConfigUtil;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截指定path，进行权限验证，及用户的本地session过期后，重新进行赋值
 */
@SuppressWarnings("ALL")
public class SmsCenterInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ConfigUtil configUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Subject subject = ShiroUtil.getShiroSubject();
        Object principal = ShiroUtil.getPrincipal(subject);
        if (subject==null || principal==null){//没有登录，跳转到没有登录页面
            Map<String,String> resultMap = new HashMap<String, String>();
            resultMap.put("code", ShiroError.LoginFailedException);
            resultMap.put("success","false");
            resultMap.put("message","当前用户已注销");
            ShiroAjaxUtil.out(response,resultMap);
            return false;
        }
        return true;
        /*
        HandlerMethod handler2=(HandlerMethod) handler;
        RequiresPermissions requiresPermissions = handler2.getMethodAnnotation(RequiresPermissions.class);
        long time = new java.util.Date().getTime();
        boolean isPermissioin = false;
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser==null || currentUser==null){//没有登录，跳转到没有登录页面
            Map<String,String> resultMap = new HashMap<String, String>();
            resultMap.put("success","false");
            resultMap.put("message","当前用户已注销");
            ShiroAjaxUtil.out(response,resultMap);
            return false;
        }
        //没有获得注解  及不需要权限-- 则直接运行
        if(null!=requiresPermissions){
            String [] permission = requiresPermissions.value();
            for(String per:permission){
                //当前登录人 具有权限
                if(currentUser.isPermitted(per)){
                    isPermissioin = true;
                    break;
                }
            }
        }else{
            isPermissioin = true;
        }

        System.out.println("拦截到了mvc方法:"+handler2.getMethod()+"方法所用时间："+time+"到"+new java.util.Date().getTime());
        if(isPermissioin){
            //有执行方法或权限不拦截
            return true;
        }else{
            //抛出无权限异常
            throw new AuthorizationException();
        }*/
    }
}
